# -*- coding:iso-8859-1 -*-
#
# Copyright @2009 - Emmanuel Br&ecute;ton
#
# Licensed under the GNU General Public License, Version 3.0 (the
# "License"); you may not use this file except in compliance with the
# License.  You may obtain a copy of the License at the root of this
# project in file LICENSE.TXT
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime

from django.http import HttpResponse, HttpResponseForbidden
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.models import User
# fall back django 0.96
try:
    from django.http import HttpResponseBadRequest
except ImportError:
    from django.http import HttpResponseServerError as HttpResponseBadRequest 

from obviews.views import View, FormView, CutResponse

# Equivalent to direct_to_template
class DirectView(View):
    template_name = "about.html"

# Adding a static variables in context, in *class* or in *instance*
# Overriding the first with the second
class EnrichedView(View):
    template_name = "welcome.html"
    defaults = {"site": "ObViews"}

# Adding a dynamic variables in context, in *calls*
class DynamicView(View):
    template_name = "greet.html"
    defaults = {"greeting": "Hello"}

# adding authentification
class PrivateView(View):
    template_name = "private.html"
    login_required = True
    
# adding variables in context at call time
class ContextView(View):
    template_name = "now.html"

    def build_params(self, request, name="guest"):
        return {"name": name,
                "now": datetime.datetime.now()}
    
# inheriting ! Even more DRY...
# adding more vars in context according given arguments passed through URL
class ComplexView(ContextView):

    def build_params(self, request, name=None, cap=None):
        params = super(ComplexView, self).build_params(request, name=name)
        params["name"] = cap=="cap" and name.upper() or name
        return params
    
# change type of response
class ForbiddenView(View):
    template_name = "forbidden.html"
    response_builder = HttpResponseForbidden

# stop process at any point
class ProcessView(View):
    template_name = "time_shift.html"

    def _some_function(self, shift):
        shift = int(shift) # integer guaranteed by regexp in URL
        if shift < -12 or shift > 12:
            raise CutResponse(HttpResponseBadRequest(
                "shift must be in [-12,12]"))
        return datetime.datetime.now()+datetime.timedelta(hours=shift)

    def build_params(self, request, shift=None):
        # calling other function for the sake of the demo, exception
        # can be raised anywhere
        return {"datetime": self._some_function(shift)}

# Need full HTML ? not response object ?
# simply call view instance with make_response=False
class DirectView(View):
    template_name = "about.html"

# You don't even have a Request object to start with ?
class RawHTMLView(View):
    template_name = "raw.html"

def print_html():
    view = RawHTMLView()
    print view(None)    # make_response=False not necessary when request is None

# All inclusive
class AllView(View):
    template_name = "all.html"
    login_required = False
    defaults = {"chapter": "all inclusive"}
    response_builder = HttpResponse

    def build_params(self, request, kwarg1=None, kwarg2=None):
        params = super(AllView, self).build_params(
            request, kwarg1=kwarg1, kwarg2=kwarg2)
        params["ip"] = request.META.get("REMOTE_ADDR", "ip not found")
        return params

# back to basic views....
from django.contrib.auth.forms import UserCreationForm
def register(request):
    if request.method == 'POST': # If the form has been submitted...
        form = UserCreationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
	    username = form.cleaned_data['username']
	    password = form.cleaned_data['password1']
	    user = User.objects.create_user(username, username+u"@nomail.com", password)
	    return HttpResponse('Account created (even if you are not logged yet). You may continue to your <a href="/private/">account</a>')
        else:
            pass
    else:
        form = UserCreationForm() # An unbound form
    return render_to_response('registration/register.html', {'form': form},
			      context_instance=RequestContext(request))
